package com.danskin.wechat.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.entity.GiftConfig;
import com.danskin.wechat.entity.WxCardConfig;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.GiftConfigService;
import com.danskin.wechat.service.WxCardConfigService;
import com.danskin.wechat.util.FTPHelper;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;

@Controller
@RequestMapping("giftCertificate")
public class GiftCertificateController extends BaseController {

	@Resource
	private GiftConfigService giftConfigService;

	@Resource
	private WxCardConfigService wxCardConfigService;

	/**
	 * 跳转到礼券管理页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "queryGiftConfigList", method = RequestMethod.GET)
	public String queryGiftConfigList() {
		return "coupon/gift_config_list";
	}

	/**
	 * 获取新人礼列表
	 * 
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryNewCustGiftList", method = RequestMethod.GET)
	public Object queryNewCustGiftList(Page page, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", 1);
		map.put("mpId", getMpId());
		page.setMap(map);
		List<GiftConfig> newCustGiftList = giftConfigService.listPageGiftConfigList(page);

		return pagelistToJSONForBootStrapTable(newCustGiftList, page);
	}

	/**
	 * 获取感恩礼列表
	 * 
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryThankfulGiftList", method = RequestMethod.GET)
	public Object queryThankfulGiftList(Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", 2);
		map.put("mpId", getMpId());
		page.setMap(map);
		List<GiftConfig> newCustGiftList = giftConfigService.listPageGiftConfigList(page);

		return pagelistToJSONForBootStrapTable(newCustGiftList, page);
	}

	/**
	 * 跳转礼券配置新建或更新页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "jumpGiftConfigAddOrUpdate", method = RequestMethod.GET)
	public String jumpGiftConfigAddOrUpdate(@RequestParam(value = "id", required = false) Integer id,
			@RequestParam(value = "errCode", required = false) String errCode, Model model) {
		if (id != null) {
			LogUtil.info("=========跳转礼券配置新建或更新页面参数：id=" + id);
		}

		GiftConfig giftConfig = new GiftConfig();
		List<WxCardConfig> wxCardConfigList = new ArrayList<WxCardConfig>();

		try {
			if (id != null) {
				giftConfig = giftConfigService.selectGiftConfigById(id);
			}

			// 查询优惠券模板
			wxCardConfigList = wxCardConfigService.selectListForGiftConfig(this.getMpId());
		} catch (Exception e) {
			LogUtil.error("========跳转礼券配置新建或更新页面异常", e);
		}
		model.addAttribute("id", id);
		model.addAttribute("giftConfig", giftConfig);
		model.addAttribute("wxCardConfigList", wxCardConfigList);
		model.addAttribute("mpId", getMpId());
		model.addAttribute("errCode", errCode);
		return "coupon/gift_config_add_or_update";
	}

	/**
	 * 执行新建或更新礼券配置
	 * 
	 * @param giftConfig
	 * @return
	 */
	@RequestMapping(value = "saveOrUpdateGiftConfig", method = RequestMethod.POST)
	public String saveOrUpdateGiftConfig(@ModelAttribute("giftConfig") GiftConfig giftConfig,
			@RequestParam(value = "picture", required = false) MultipartFile file) {
		LogUtil.info("========新建或更新礼券配置参数：" + ToStringBuilder.reflectionToString(giftConfig));

		try {
			int insertOrUpdateCount = 0;
			if (giftConfig != null) {
				giftConfig.setMpId(this.getMpId());
				String filetemp = System.getProperty("catalina.home") + File.separator + "danskin-temp";
				if (giftConfig.getId() == null) { // id为空，执行插入
					// 如果是新建并且奖品类型为实物，那么商品图片必传
					if (StringUtils.equals(DanskinConstants.GIFT_CONFIG_PRIZE_TYPE_PRODUCT, giftConfig.getPrizeType())) {
						// 上传图片到ftp服务器并返回图片地址
						String pictureUrl = FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "giftConfig",
								filetemp);
						giftConfig.setPicUrl(pictureUrl);
					}

					if (giftConfig.getPoints() == null) {
						giftConfig.setPoints(0);
					}
					if (StringUtils.isBlank(giftConfig.getCouponTemplateId())) {
						giftConfig.setCouponTemplateId("0");
					}
					giftConfig.setUsedQty(0);
					insertOrUpdateCount = giftConfigService.insertGiftConfig(giftConfig);
				} else { // id不为空，执行更新
					if (file != null && file.getSize() > 0) {
						// 上传图片到ftp服务器并返回图片地址
						String pictureUrl = FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "giftConfig",
								filetemp);
						giftConfig.setPicUrl(pictureUrl);
					}
					insertOrUpdateCount = giftConfigService.updateGiftConfig(giftConfig);
				}
				// 如果insertOrUpdateCount不为0，表示插入或更新成功
				if (insertOrUpdateCount > 0) {
					return "redirect:/giftCertificate/queryGiftConfigList";
				} else if (insertOrUpdateCount == -1) {
					String param = "";
					if (giftConfig.getId() != null) {
						param = "?id=" + giftConfig.getId();
					}
					param = (param != "" ? param + "&" : "?") + "errCode=-1";
					return "redirect:/giftCertificate/jumpGiftConfigAddOrUpdate" + param;
				}
			}
		} catch (Exception e) {
			LogUtil.error("=========新建或更新礼券配置异常", e);
		}
		return "redirect:/giftCertificate/queryGiftConfigList";
	}

	/**
	 * 删除礼券配置
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "deleteGiftConfig", method = RequestMethod.POST)
	public AccessResponse<String> deleteGiftConfig(@RequestParam("id") Integer id) {
		if (id != null) {
			LogUtil.info("=======删除礼券配置参数：id=" + id);
		}

		int deleteCount = 0;

		try {
			deleteCount = giftConfigService.deleteGiftConfigById(id);

			if (deleteCount > 0) {
				return new AccessResponse<String>("success", "删除礼券配置成功");
			}
		} catch (Exception e) {
			LogUtil.error("========删除礼券配置异常", e);
		}
		return new AccessResponse<String>("fail", "删除礼券配置失败");
	}

}
